from typing import Optional

from fastapi import APIRouter, Query, Form

from model.backtest import BackTest
from pojo.response import Response
from service import dataService
from service.strategyService import Movement
from utils.utils import is_empty

backtestRouter = APIRouter(tags=['backtest'])


@backtestRouter.post('/IntradayMovementStrategy',
                     summary='日内动量策略回测',
                     description='返回回测交易订单和评估指标')
async def post_IntradayMovementStrategy(
    code: str = Form(description='股票代码'),
    window: Optional[str] = Form(None, description='时间窗口, 默认为None'),
    start_date: Optional[str] = Form(None, description='起始日期, 默认为None'),
    end_date: Optional[str] = Form(None, description='结束日期, 默认为None'),
    cash: Optional[str] = Form('10000', description='起始资金, 默认为10000'),
    commission: Optional[str] = Form('0.001', description='佣金比例, 默认为0.001'),
    hands: Optional[str] = Form('1', description='单次手数, 默认为1'),
    period: Optional[str] = Form('15', description='周期, 默认为15'),
):
    # 参数处理
    if isinstance(code, str) and is_empty(code):
        return Response(
            code=0,
            message="参数错误: 股票代码(code)参数不能为空!"
        )

    if isinstance(window, str):
        if is_empty(window):
            window = None
        else:
            window = int(window)

    if isinstance(start_date, str) and is_empty(start_date):
        start_date = None
    if isinstance(end_date, str) and is_empty(end_date):
        end_date = None

    backtest = BackTest()

    if isinstance(cash, str):
        if not is_empty(cash):
            cash = int(cash)
            backtest.broker.setCash(cash)

    if isinstance(commission, str):
        if not is_empty(commission):
            commission = float(commission)
            backtest.broker.setCommission(commission)

    if isinstance(hands, str):
        if not is_empty(hands):
            hands = int(hands)
            backtest.broker.setHands(hands)

    _ ,df = await dataService.get_stockHistList(
        code=code,
        start_date=start_date,
        end_date=end_date,
        window=window,
        period=period
    )

    backtest.setData(df)
    model = Movement.IntradayMovementStrategy(period=period, window=window, code=code, rule=1)
    backtest.setStrategy(model)
    orderHistory, evaluate = await backtest.run()

    return Response(
        code=1,
        data={
            'orderHistory': orderHistory,
            'evaluate': evaluate,
        },
        message='日内动量策略回测成功!'
    )




